package com.cseg674.dataquery.authentication;

import java.sql.*;
import java.io.*;


public class Mysql {

  private Connection conn = null;
  private Statement stmt = null;
  private PreparedStatement prepstmt = null;


  public Mysql() {
    try {
      Class.forName(Constants.dbdriver);
      conn = DriverManager.getConnection(Constants.dburl);
      stmt = conn.createStatement();
    } catch (Exception e) {
      System.err.println("Mysql init error: " + e);
    }
  }


  public Mysql(String sql) {
    try {
      Class.forName(Constants.dbdriver);
      conn = DriverManager.getConnection(Constants.dburl);
      prepareStatement(sql);
    } catch (Exception e) {
      System.err.println("Mysql init error: " + e);
    }

  }

  public Connection getConnection() {
    return conn;
  }

  public void prepareStatement(String sql) throws SQLException {
    prepstmt = conn.prepareStatement(sql);
  }

  public void setString(int index, String value) throws SQLException {
    prepstmt.setString(index, value);
  }

  public void setInt(int index, int value) throws SQLException {
    prepstmt.setInt(index, value);
  }

  public void setBoolean(int index, boolean value) throws SQLException {
    prepstmt.setBoolean(index, value);
  }

  public void setDate(int index, Date value) throws SQLException {
    prepstmt.setDate(index, value);
  }

  public void setLong(int index, long value) throws SQLException {
    prepstmt.setLong(index, value);
  }

  public void setFloat(int index, float value) throws SQLException {
    prepstmt.setFloat(index, value);
  }

  public void setBinaryStream(int index, InputStream in, int length) throws
      SQLException {
    prepstmt.setBinaryStream(index, in, length);
  }

  public void clearParameters() throws SQLException {
    prepstmt.clearParameters();
  }

  public PreparedStatement getPreparedStatement() {
    return prepstmt;
  }

  public Statement getStatement() {
    return stmt;
  }

  public ResultSet executeQuery(String sql) throws SQLException {
    if (stmt != null) {
      return stmt.executeQuery(sql);
    } else
      return null;
  }

 
  public ResultSet executeQuery() throws SQLException {
    if (prepstmt != null) {
      return prepstmt.executeQuery();
    } else
      return null;
  }


  public void executeUpdate(String sql) throws SQLException {
    if (stmt != null)
      stmt.executeUpdate(sql);
  }

  public void executeUpdate() throws SQLException {
    if (prepstmt != null)
      prepstmt.executeUpdate();
  }


  public void close() {
    try {
      if (stmt != null) {
        stmt.close();
        stmt = null;
      }
      if (prepstmt != null) {
        prepstmt.close();
        prepstmt = null;
      }
      conn.close();
      conn = null;
    } catch (Exception e) {
      System.err.println("Mysql close error: " + e);
    }

  }
}